﻿using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using log4net;
using MPMovieCatalog.Exception;

namespace MPMovieCatalog.Service
{
    class MovieServiceFactory
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(MovieServiceFactory));

        private static IMovieService m_movieService = null;

        private static IChannel m_channel = null;

        private static bool m_initialized = false;

        public static IMovieService getMovieService()
        {
            if (!m_initialized)
            {
                throw new MPMovieCatalogException("MovieServiceFactory isnt initialized!");
            }

            return m_movieService;
        }

        public static bool IsInitialized
        {
            get { return m_initialized; }
        }

        public static void Initialize(string host, decimal port)
        {
            try
            {
                m_initialized = false;

                if (m_channel != null)
                {
                    ChannelServices.UnregisterChannel(m_channel);
                }
                m_channel = new HttpClientChannel();
                ChannelServices.RegisterChannel(m_channel, false);
                m_movieService = (IMovieService)Activator.GetObject(typeof(IMovieService)
                                   , string.Format("http://{0}:{1}/MovieService", host, port));
                m_movieService.Check();
                m_initialized = true;
            }
            catch (System.Exception ex)
            {
                log.Error(string.Format("Error initializing MovieServiceFactory, message: {0}", ex.Message), ex);
                throw new MPMovieCatalogException("Error initializing MovieServiceFactory", ex);
            }
        }

    }
}
